package com.tailyou.hms.firstapp.act;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.tailyou.hms.firstapp.R;
import com.tailyou.hms.firstapp.bean.JsonBean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpActivity extends AppCompatActivity {

    private TextView tvContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ok_http);
        tvContent = findViewById(R.id.tvContent);
        findViewById(R.id.btnPost).setOnClickListener(v -> doPost("https://www.wanandroid.com/user/login"));
        findViewById(R.id.btnGet).setOnClickListener(v -> doGet("https://www.wanandroid.com/article/list/0/json"));
        findViewById(R.id.btnDownload).setOnClickListener(v -> doDownload("https://api.worldskills.org/resources/download/12481/14919/15847?l=en"));
    }

    /**
     * GET请求
     *
     * @param url
     */
    private void doGet(String url) {
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(url).build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String repContent = response.body().string();
                        runOnUiThread(() -> tvContent.setText(repContent));

                        Gson gson = new Gson();
                        JsonBean javaBean = gson.fromJson(repContent, JsonBean.class);

                        Log.d("Http", repContent);
                    } else {
                        runOnUiThread(() -> tvContent.setText("请求失败"));
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * POST请求
     *
     * @param url
     */
    private void doPost(String url) {
        try {
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            /*MediaType mediaType = MediaType.parse("application/json");
            String requestBody = "{\"username\": \"tailyou04\", \"password\": \"tailyou02\"}";*/
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            String requestBody = "username=" + URLEncoder.encode("tailyou04", "utf-8") + "&password=" + URLEncoder.encode("tailyou02", "utf-8");
            RequestBody body = RequestBody.create(mediaType, requestBody);
            Request request = new Request.Builder().url(url).post(body).build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String repContent = response.body().string();
                        runOnUiThread(() -> tvContent.setText(repContent));
                        Log.d("Http", repContent);
                    } else {
                        runOnUiThread(() -> tvContent.setText("请求失败"));
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件下载
     *
     * @param url
     */
    private void doDownload(String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(url).build();
                try {
                    Response response = client.newCall(request).execute();
                    InputStream inputStream = response.body().byteStream();
                    File externalFilesDir = ContextCompat.getExternalFilesDirs(OkHttpActivity.this, Environment.DIRECTORY_DOWNLOADS)[0];
                    File file = new File(externalFilesDir, System.currentTimeMillis() + ".pdf");
                    OutputStream outputStream = new FileOutputStream(file);
                    byte[] buffer = new byte[4096];
                    int len;
                    while ((len = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, len);
                    }
                    runOnUiThread(() -> tvContent.setText("下载完成"));
                    inputStream.close();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 文件上传
     *
     * @param file
     * @param url
     */
    private void doUpload(File file, String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), file);
                RequestBody requestBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("file", file.getName(), body)
                        .build();
                Request request = new Request.Builder().url(url).post(requestBody).build();
                try {
                    // 发送请求并获取响应
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        runOnUiThread(() -> tvContent.setText("上传成功"));
                    } else {
                        runOnUiThread(() -> tvContent.setText("上传失败"));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}